/*
 * Copyright 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.matto1990.app.madlab.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;

import android.app.IntentService;
import android.app.Service;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.net.Uri;
import android.text.format.DateUtils;
import android.util.Log;

import com.matto1990.app.madlab.provider.MadlabContract.Events;
import com.matto1990.app.madlab.provider.MadlabContract.Meetups;

/**
 * Background {@link Service} that synchronizes data living in
 * {@link ScheduleProvider}. Reads data from both local {@link Resources} and
 * from remote sources, such as a spreadsheet.
 */
public class SyncService extends IntentService {
    private static final String TAG = "Madlab.SyncService";
    
    public static final String ACTION_STATUS = "com.matto1990.app.madlab.sync.ACTION_STATUS";

    public static final String BROADCAST_START = "com.matto1990.app.madlab.sync.BROADCAST_START";
    public static final String BROADCAST_FINISH = "com.matto1990.app.madlab.sync.BROADCAST_FINISH";
    public static final String BROADCAST_STATUS = "com.matto1990.app.madlab.sync.BROADCAST_STATUS";
    
    private Intent broadcastStartSync = new Intent(BROADCAST_START);
    private Intent broadcastFinishSync = new Intent(BROADCAST_FINISH);
    private Intent broadcastStatus = new Intent(BROADCAST_STATUS);
    
    public static final String STATUS = "status";
    public static final String BUNDLE = "bundle";
    
    public static final int STATUS_SYNC_RUNNING = 0x1;
    public static final int STATUS_SYNC_ERROR = 0x2;
    public static final int STATUS_SYNC_FINISHED = 0x3;

    private static final int SECOND_IN_MILLIS = (int) DateUtils.SECOND_IN_MILLIS;

    /** iCal feed for events */
    private static final String ICAL_URL = "http://madlab.org.uk/?ical";

    private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
    private static final String ENCODING_GZIP = "gzip";

    public static final int STATUS_RUNNING = 0x1;
    public static final int STATUS_NOT_RUNNING = 0x2;
    
    private HttpClient httpClient;
    private ContentResolver resolver;

    private boolean syncing;

    public SyncService() {
        super(TAG);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        httpClient = getHttpClient(this);
        resolver = getContentResolver();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "onHandleIntent(intent=" + intent.toString() + ")");
        final String action = intent.getAction();
        if (action.equals(Intent.ACTION_SYNC)) {
            syncAction(intent);
        }
        else if (action.equals(ACTION_STATUS)) {
            statusAction(intent);
        }
    }
    
    private void statusAction(Intent intent) {
        if (syncing) {
            broadcastStatus.putExtra(STATUS, STATUS_RUNNING);
        }
        else {
            broadcastStatus.putExtra(STATUS, STATUS_NOT_RUNNING);
        }
        
        sendBroadcast(broadcastStatus);
    }

    private void syncAction(Intent intent) {
        syncing = true;
        
        sendBroadcast(broadcastStartSync);

        try {
            // Check the events
            final long startRemote = System.currentTimeMillis();
            
            // Get the ical data
            final HttpUriRequest request = new HttpGet(ICAL_URL);
            final HttpResponse response = httpClient.execute(request);
            
            // Check the http status code is correct
            final int status = response.getStatusLine().getStatusCode();
            if (status != HttpStatus.SC_OK) {
                throw new Exception("Unexpected server response " + response.getStatusLine() + " for " + request.getRequestLine());
            }
            
            // Get the response as an BufferedReader
            final InputStream input = response.getEntity().getContent();
            final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
            
            // TODO: Move this into a seperate method
            // Used to get the event information
            final SimpleDateFormat icalDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
            final SimpleDateFormat sqlDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            boolean inEvent = false;
            Cursor results;
            String line;
            String[] lineParts;
            String command;
            String data;
            String[] summaryParts;
            Uri eventUri;
            Uri meetupUri;
            ContentValues values;
            
            // Store the event information while looping
            String eventName = null;
            String meetupTitle = null;
            String meetupDescription = null;
            String meetupStartDateTime = null;
            String meetupEndDateTime = null;
            String meetupLocation = null;
            
            while ((line = bufferedReader.readLine()) != null) {
                if (line.startsWith("BEGIN:VEVENT")) {
                    inEvent = true;
                }
                else if (inEvent) {
                    if (line.startsWith("END:VEVENT")) {
                        inEvent = false;
                        //Log.i(TAG, "Event: " + eventName + ":" + meetupTitle + ":" + meetupStartDateTime + ":" + meetupEndDateTime + ":" + meetupLocation);
                        
                        // Check if an event for this ical entry already exists
                        eventUri = Events.buildEventUri(Events.generateEventId(eventName));
                        results = resolver.query(eventUri, null, null, null, null);
                        if (results.getCount() == 0) {
                            // If not add one
                            values = new ContentValues();
                            values.put(Events.EVENT_ID, Events.generateEventId(eventName));
                            values.put(Events.EVENT_TITLE, eventName);
                            
                            resolver.insert(Events.CONTENT_URI, values);
                        }
                        results.close();
                        
                        // Check if a meetup already exists in db
                        meetupUri = Meetups.buildMeetupUri(Meetups.generateMeetupId(eventName, meetupStartDateTime));
                        results = resolver.query(meetupUri, null, null, null, null);
                        if (results.getCount() == 0) {
                            // If not add it
                            values = new ContentValues();
                            values.put(Meetups.MEETUP_ID, Meetups.generateMeetupId(eventName, meetupStartDateTime));
                            values.put(Meetups.EVENT_ID, Events.generateEventId(eventName));
                            values.put(Meetups.MEETUP_TITLE, meetupTitle);
                            values.put(Meetups.MEETUP_DESCRIPTION, meetupDescription);
                            values.put(Meetups.MEETUP_START_DATETIME, meetupStartDateTime);
                            values.put(Meetups.MEETUP_END_DATETIME, meetupEndDateTime);
                            values.put(Meetups.MEETUP_LOCATION, meetupLocation);
                            
                            try {
                                resolver.insert(Meetups.CONTENT_URI, values);
                            }
                            catch (SQLiteConstraintException e) {
                                Log.w(TAG, "Possible duplicate meetup. " + values, e);
                            }
                        }
                        results.close();
                        
                        // Reset the data variables to null
                        eventName = null;
                        meetupTitle = null;
                        meetupDescription = null;
                        meetupStartDateTime = null;
                        meetupEndDateTime = null;
                        meetupLocation = null;
                    }
                    else {
                        // Get the command and the data
                        lineParts = line.split(":", 2);
                        command = lineParts[0];
                        data = lineParts[1];
                        
                        if (command.equalsIgnoreCase("DTSTART")) {
                            meetupStartDateTime = sqlDateFormat.format(icalDateFormat.parse(data));
                        }
                        else if (command.equalsIgnoreCase("DTEND")) {
                            meetupEndDateTime = sqlDateFormat.format(icalDateFormat.parse(data));
                        }
                        else if (command.equalsIgnoreCase("SUMMARY")) {
                            // Split the title by " - "
                            summaryParts = data.split(" - ", 2);
                            // The part before the " - " is the event name
                            eventName = summaryParts[0];
                            // The second part (if exists) is the title of that specific meetup
                            if (summaryParts.length > 1) {
                                meetupTitle = summaryParts[1];
                            }
                        }
                        else if (command.equalsIgnoreCase("DESCRIPTION")) {
                            meetupDescription = data;
                        }
                        else if (command.equalsIgnoreCase("LOCATION")) {
                            if (data.contains("Upstairs")) {
                                meetupLocation = "Upstairs";
                            }
                            else if (data.contains("Downstairs")) {
                                meetupLocation = "Downstairs";
                            }
                        }
                    }
                }
            }
            
            
            Log.d(TAG, "remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");
            
            // Announce success to any surface listener
            Log.d(TAG, "sync finished");
            broadcastFinishSync.putExtra(STATUS, STATUS_SYNC_FINISHED);
            sendBroadcast(broadcastFinishSync);
        }
        catch (Exception e) {
            Log.e(TAG, "Problem while syncing", e);

            // Pass back error to surface listener
            broadcastFinishSync.putExtra(Intent.EXTRA_TEXT, e.toString());
            broadcastFinishSync.putExtra(STATUS, STATUS_SYNC_ERROR);
            sendBroadcast(broadcastFinishSync);
        }
        
        syncing = false;
    }

    /**
     * Generate and return a {@link HttpClient} configured for general use,
     * including setting an application-specific user-agent string.
     */
    public static HttpClient getHttpClient(Context context) {
        final HttpParams params = new BasicHttpParams();

        // Use generous timeouts for slow mobile networks
        HttpConnectionParams.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS);
        HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS);

        HttpConnectionParams.setSocketBufferSize(params, 8192);
        HttpProtocolParams.setUserAgent(params, buildUserAgent(context));

        final DefaultHttpClient client = new DefaultHttpClient(params);
        
        // Allow gzip content
        client.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(HttpRequest request, HttpContext context) {
                // Add header to accept gzip content
                if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                    request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
                }
            }
        });
        client.addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(HttpResponse response, HttpContext context) {
                // Inflate any responses compressed with gzip
                final HttpEntity entity = response.getEntity();
                final Header encoding = entity.getContentEncoding();
                if (encoding != null) {
                    for (HeaderElement element : encoding.getElements()) {
                        if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                            response.setEntity(new InflatingEntity(response.getEntity()));
                            break;
                        }
                    }
                }
            }
        });

        return client;
    }

    /**
     * Build and return a user-agent string that can identify this application
     * to remote servers. Contains the package name and version code.
     */
    private static String buildUserAgent(Context context) {
        try {
            final PackageManager manager = context.getPackageManager();
            final PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);

            // Some APIs require "(gzip)" in the user-agent string.
            return info.packageName + "/" + info.versionName + " (" + info.versionCode + ") (gzip)";
        } catch (NameNotFoundException e) {
            return null;
        }
    }

    /**
     * Simple {@link HttpEntityWrapper} that inflates the wrapped
     * {@link HttpEntity} by passing it through {@link GZIPInputStream}.
     */
    private static class InflatingEntity extends HttpEntityWrapper {
        public InflatingEntity(HttpEntity wrapped) {
            super(wrapped);
        }

        @Override
        public InputStream getContent() throws IOException {
            return new GZIPInputStream(wrappedEntity.getContent());
        }

        @Override
        public long getContentLength() {
            return -1;
        }
    }
}
